//
//  EditUserViewController.m
//  cliqset
//
//  Created by David Hinson on 2/20/09.
//  Copyright 2009 Sumner Systems Management, Inc.. All rights reserved.
//

#import "EditUserViewController.h"
#import "cliqsetAppDelegate.h"
#import "Contact.h"

@implementation EditUserViewController

@synthesize parent;
@synthesize userTable;
@synthesize givenNameField;
@synthesize familyNameField;
@synthesize positionField;
@synthesize companyField;

@synthesize givenName;
@synthesize familyName;
@synthesize position;
@synthesize company;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	self.title = @"Edit User";
	
	self.userTable.backgroundColor = [UIColor clearColor];
	
	// Set save button
	UIBarButtonItem* saveButton = [[[UIBarButtonItem alloc] initWithTitle:@"Save" style:UIBarButtonItemStyleBordered target:self action:@selector(doSave:)] retain];
	self.navigationItem.rightBarButtonItem = saveButton;
	
	// Set cancel button
	UIBarButtonItem* cancelButton = [[[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStyleBordered target:self action:@selector(doCancel:)] retain];
	self.navigationItem.leftBarButtonItem = cancelButton;
}

// Do cancel
-(void)doCancel:(id)id {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	NSLog(@"doCancel");
	
	[myApp slideIMOut];
}

// Do save
-(void)doSave:(id)id {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	if ([self.givenNameField isEqualToString:@""] && [self.familyNameField isEqualToString:@""]) {
		[myApp addTextToLog:@"User Name Cannot Be Empty!" withCaption:@"Edit User" ];
		return;
	}
	
	// Dereference our contact
	Contact *contact=nil; 
	if (self.parent.index>=0) {
	if (parent.isFavorite) {
		for (int x=0; x<[myApp.contacts count]; x++) {
			Contact *localContact = (Contact*)[myApp.contacts objectAtIndex:x]; 
			if ([localContact.contactIdentifier isEqualToString:[myApp.favorites objectAtIndex:parent.index]]) {
				contact = localContact;
				break;
			}
		}
	} 
	else {
		contact = (Contact *)[myApp.contacts objectAtIndex:parent.index];
	}
	} else {
		contact = self.parent.bufferContact;
	}
	
	NSLog(@"doSave");
	
	contact.givenName  = self.givenNameField;
	contact.familyName = self.familyNameField;
	contact.position   = self.positionField == nil ? @"" : self.positionField;
	contact.company    = self.companyField == nil ? @"" : self.companyField;
	
	// Add through cliqset, if editing
	if (self.parent.index>=0) {
		[myApp.cliqset putContact:contact];
		}
	
	parent.myName.text = (NSMutableString*)[@"" stringByAppendingFormat:@"%@ %@", self.givenNameField, self.familyNameField];
	parent.myJob.text  = (NSMutableString*)[@"" stringByAppendingFormat:@"%@", self.companyField];
	
	[myApp slideUserOut];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
}

// Number of table sections
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return 1;
}

// Return rows in table
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	
	switch (section) {
		case 0:
			return 4.0;
			break;
			
		default:
			return 0;
			break;
	}
}

// Set row height
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	
	switch (indexPath.section) {
		case 0:
			return 40.0;
			break;
		default:
			break;
	}
	
	return 0.0;
}

// Indicate disclosure
- (UITableViewCellAccessoryType)tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath
{
	if (indexPath.section == 1 && indexPath.row == 0) {
		return UITableViewCellAccessoryDisclosureIndicator;	
	} 
	else {
		return UITableViewCellAccessoryNone;
	}
}

// Draw cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	
	UITableViewCell *cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:nil] autorelease];
    [cell backgroundView].opaque=YES;
    [cell backgroundView].clearsContextBeforeDrawing;
   	[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
	
	UIFont* large_font      = [UIFont systemFontOfSize:18];
	UIColor* textColor      = [UIColor colorWithRed:85.0/255.0 green:85.0/255.0 blue:85.0/255.0 alpha:1.0];
	
	cell.hidesAccessoryWhenEditing = NO;
	
	if (givenName) {		
		[givenName release];
		givenName = nil;
		}
	if (familyName) {
		[familyName release];
		familyName = nil;
		}
	if (position) {
		[position release];
		position = nil;
		}
	if (company) {
		[company release];
		company = nil;
		}
	
	givenName  = [[UITextField alloc] initWithFrame:CGRectMake(20,7,290,38)];
	familyName = [[UITextField alloc] initWithFrame:CGRectMake(20,7,290,38)];
	position   = [[UITextField alloc] initWithFrame:CGRectMake(20,7,290,38)];
	company    = [[UITextField alloc] initWithFrame:CGRectMake(20,7,290,38)];
	
	switch (indexPath.row) {
		case 0:
			
			givenName.textColor   = textColor;
			givenName.font        = large_font;
			givenName.placeholder = @"Given Name";
			
			givenName.autocapitalizationType = UITextAutocapitalizationTypeWords;
			[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(givenNameDidChange:) name:@"UITextFieldTextDidChangeNotification" object:givenName];
			givenName.text         = (!self.givenNameField || [self.givenNameField isEqualToString:@""]) ? @"" : self.givenNameField;
			
			[givenName becomeFirstResponder];
			
			[cell addSubview:givenName];
			
			break;
			
		case 1:
			
			familyName.textColor   = textColor;
			familyName.font        = large_font;
			familyName.placeholder = @"Family Name";
			
			familyName.autocapitalizationType = UITextAutocapitalizationTypeWords;
			[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(familyNameDidChange:) name:@"UITextFieldTextDidChangeNotification" object:familyName];
			familyName.text         = (!self.familyNameField || [self.familyNameField isEqualToString:@""]) ? @"" : self.familyNameField;
			
			[cell addSubview:familyName];
			
			break;
			
		case 2:
			
			position.textColor   = textColor;
			position.font        = large_font;
			position.placeholder = @"Position";
			
			position.autocapitalizationType = UITextAutocapitalizationTypeWords;
			[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(positionDidChange:) name:@"UITextFieldTextDidChangeNotification" object:position];
			position.text         = (!self.positionField	|| [self.positionField isEqualToString:@""]) ? @"" : self.positionField;
			
			[cell addSubview:position];
			
			break;
			
		case 3:
			
			company.textColor   = textColor;
			company.font        = large_font;
			company.placeholder = @"Company";
			
			company.autocapitalizationType = UITextAutocapitalizationTypeWords;
			[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(companyDidChange:) name:@"UITextFieldTextDidChangeNotification" object:company];
			company.text         = (!self.companyField	|| [self.companyField isEqualToString:@""]) ? @"" : self.companyField;
			
			[cell addSubview:company];
			
			break;
	}
	
	UIColor* myBGColor               = [UIColor colorWithRed:248.0/255.0 green:248.0/255.0 blue:248.0/255.0 alpha:1.0];
	cell.backgroundView.backgroundColor = myBGColor;
	for ( UIView* view in cell.contentView.subviews ) 
	{
		view.backgroundColor = [ UIColor clearColor ];
	}
	
	return cell;
}	

// Row selected... 
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {	
	//cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	NSLog(@"didSelectRowAtIndexPath");
	
	UITableViewCell *hitCell = [tableView cellForRowAtIndexPath:indexPath];	
    [hitCell setSelected:NO animated:YES];
}

// Our given name changed... save it
-(void)givenNameDidChange:(id)textField {	
	self.givenNameField = (NSMutableString*)[[textField object] text];
}

// Our family name changed... save it
-(void)familyNameDidChange:(id)textField {	
	self.familyNameField = (NSMutableString*)[[textField object] text];
}

// Our position changed... save it
-(void)positionDidChange:(id)textField {	
	self.positionField = (NSMutableString*)[[textField object] text];
}

// Our company changed... save it
-(void)companyDidChange:(id)textField {	
	self.companyField = (NSMutableString*)[[textField object] text];
}

- (void)dealloc {
	
	[givenName release];
	[familyName release];
	[company release];
	[position release];
	
	[parent release];
	[userTable release];
	[givenNameField release];
	[familyNameField release];
	[positionField release];
	[companyField release];
    [super dealloc];
}


@end
